import React, { memo } from "react";
import { Route, Switch, Redirect } from "react-router-dom";
import { useSessionStorageState } from 'ahooks';
import Login from 'pages/Login';
import routesConfig from "./config";

function RouteWithSubRoutes(route) {
    const [isLogin] = useSessionStorageState('isLogin', false);
    return (
        <Route
            path={route.path}
            render={(props) => (isLogin ? <route.component {...props} routes={route.routes}>
                {route.children ? route.children.map((child, i) => (
                    /** 递归传入子组件 */
                    <RouteWithSubRoutes key={i} {...child} />
                )) : ''}
            </route.component> : <Redirect to="/login"/>)}
        />
    );
}

const RouterPage = memo(() => {
    return (
        <Switch>
            <Route path="/login" render={(props) => <Login {...props}></Login>}></Route>
            {routesConfig.map((item, index) => (
                item.component ? <RouteWithSubRoutes key={index} {...item} /> : null
            ))}
        </Switch>
    );
});

export default RouterPage;